﻿using Castle.DynamicProxy;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace AspNetCore.HttpClientAndPolly.PollyHelper
{
    /// <summary>
    /// Api动态代理
    /// </summary>
    public class RequestApiProxy
    {
        /// <summary>
        /// Get
        /// </summary>
        public static async Task<T> Get<T>(HttpClient httpClient, string url, object param = null) where T : class, new()
        {
            return await SoftInvoke(async () =>
            {
                ProxyGenerator generator = new ProxyGenerator();
                CustomInterceptor interceptor = new CustomInterceptor();
                RequestApi requestApi = generator.CreateClassProxy<RequestApi>(interceptor);
                return await requestApi.Get<T>(httpClient, url, param);
            });
        }

        public static async Task<T> Post<T>(HttpClient httpClient, string url, object param) where T : class, new()
        {
            return await SoftInvoke(async () =>
            {
                ProxyGenerator generator = new ProxyGenerator();
                CustomInterceptor interceptor = new CustomInterceptor();
                RequestApi requestApi = generator.CreateClassProxy<RequestApi>(interceptor);
                return await requestApi.Post<T>(httpClient, url, param);
            });
        }

        /// <summary>
        /// 异常捕获拦截通用方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public static async Task<T> SoftInvoke<T>(Func<Task<T>> func) where T : class, new()
        {
            try
            {
                return await func();
            }
            catch (Exception ex)
            {
                //记录日志 默认放回一个空的对象避免报错
                Console.WriteLine(ex.Message);
                return new T();
            }
        }
    }
}
